package com.aspire.nm.component.miniServer.protocol;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.aspire.nm.component.util.RandomUtil;
import org.apache.commons.lang3.StringUtils;

import com.aspire.nm.component.miniServer.plugin.SessionCacher;


public class Request {

    private String clientEncode;
    public Request(String clientEncode){
        this.clientEncode = clientEncode;
    }
	private boolean isGet;
	private int contentLength;
	private byte[] postdate;
	private String path;
	private Hashtable<String,String> params = new Hashtable<String,String>();
	private Hashtable<String,String> headers = new Hashtable<String,String>();
	private Map<String,Object> session;
	private String jsessionid;
	private String extName;
	
    
    
	
    
    
    public String getJsessionid() {
        return jsessionid;
    }
    public void setJsessionid(String jsessionid) {
        this.jsessionid = jsessionid;
    }

    public Map<String, Object> getSession() {
        return session;
    }
    
    public void setSession(Map<String, Object> session) {
        this.session = session;
    }
    public String getExtName() {
        return extName;
    }
    
    
    
    public void setSession(SessionCacher cacher){
        String cookie = headers.get("Cookie");
        if(cookie != null){
            String [] cookie_k_v = cookie.trim().split("=");
            if(cookie_k_v.length == 2){
                jsessionid = cookie_k_v[1];
                session = cacher.get(jsessionid);
            }
        }
        if(session == null){
            jsessionid = java.util.UUID.randomUUID() + RandomUtil.getRandomStr(8);
            session = new HashMap<String,Object>();
        }
    }
    
    
    
    public void setExtName() {
        if(StringUtils.isEmpty(path))return;
        if(path.endsWith("/") || path.endsWith("\\")){
    		path = path.substring(0,path.length()-1);
    	}
        Pattern pattern = Pattern.compile("[^/\\\\]+$");
        Matcher matcher = pattern.matcher(path);
        matcher.find();
        
        String fileName = matcher.group();
        String extName = null;
        Matcher m1 = Pattern.compile("(.*)(\\.)(.*)").matcher(fileName);
        if(m1.find() && !m1.group(3).equals("")){
            extName = "."+m1.group(3);
        }
        if(extName != null){
            if(extName.equalsIgnoreCase(".do")||extName.equalsIgnoreCase(".action")){
                path = path.substring(0,path.indexOf(extName));
                extName = null;
            }
        }
        this.extName = extName;
    }
    public Hashtable<String,String> getParams() {
		return params;
	}
	public String getParamString() {
		String result = "";
		for(Iterator<String> itr = params.keySet().iterator(); itr.hasNext();){ 
			String key = (String) itr.next(); 
			String value = (String) params.get(key);
			result += "["+key+" = "+value+"]  ";
		}
		return result;
	}
	
	public void setParams(String paramsContent) throws UnsupportedEncodingException {
		String kvs [] = paramsContent.trim().split("&");
		for(String kv:kvs){
			if(kv.indexOf("=") != -1){
				String key = kv.split("=")[0].trim();
				String value = kv.substring((key+"=").length());
				
				params.put(key, java.net.URLDecoder.decode(value,clientEncode));
			}
		}
	}

	
	public Hashtable<String, String> getHeaders() {
		return headers;
	}
	public void setHeaders(Hashtable<String, String> headers) {
		this.headers = headers;
	}
	public String getPath() {
		return path;
	}

	public void setPath(String path) {
		this.path = path;
	}

	
	
	public String getPostdate() {
	    if(headers.get("Content-Type") != null && headers.get("Content-Type").trim().equals("application/x-www-form-urlencoded")){
	        try {
                return java.net.URLDecoder.decode(new String(postdate), clientEncode);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
                return null;
            }
	    }else{
	        return new String(postdate);
	    }
	}
	public byte[] getPostdateBytes() {
	    return postdate;
	}
	public void setPostdate(byte[] postdate) {
	    this.postdate = postdate;
	}

	
	
	
	
	public int getContentLength() {
		return contentLength;
	}

	public void setContentLength(int contentLength) {
		this.contentLength = contentLength;
	}

	public boolean isGet() {
		return isGet;
	}

	public void setGet(boolean isGet) {
		this.isGet = isGet;
	}
	
	
	public String toString(){
		return "isGet = " + isGet + " contentLength = " + contentLength +" postdate = " + postdate+ " path = " + path +" params = " + getParamString();
	}
}
